<template>
  <el-dialog
    :title="view === 'create'? '开户': '编辑'"
    :visible="true"
		width="50%"
    custom-class="companydialogWrapper"
    :before-close="closeDialog">
    <el-form :model="formData" label-width="120px" ref="ruleForm" :rules="rules">
      <el-form-item label="企业名称" prop="companyName">
        <el-input v-model.trim="formData.companyName" auto-complete="off"></el-input>
      </el-form-item>
			<el-form-item label="企业规模" prop="companyScale" required>
				<el-select v-model="formData.companyScale">
					<el-option 
						v-for="item in compList"
						:key="item.sortNumber"
						:label="item.companyScaleName"
						:value="item.companyScaleNo"
					></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="企业类型" prop="companyType">
        <el-input v-model.trim="formData.companyType" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="企业简介" prop="companyDesc">
        <el-input
          v-model.trim="formData.companyDesc"
          type="textarea"
          class="textarea"
         auto-complete="off"></el-input>
      </el-form-item>
			<el-form-item label="企业联系人" prop="contractPerson">
        <el-input v-model.trim="formData.contractPerson" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="企业联系电话" prop="contractPhone">
        <el-input v-model.trim="formData.contractPhone" auto-complete="off"></el-input>
      </el-form-item>
			<el-form-item label="企业联系邮箱" prop="email">
        <el-input v-model.trim="formData.email" auto-complete="off"></el-input>
      </el-form-item>
			<el-form-item label="企业地址" prop="companyAddress">
        <el-input v-model.trim="formData.companyAddress" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="企业logo" prop="companyLogoUrl">
      	<div class="editImg" v-if="imgShow === 'edit' && formData.companyLogoUrl != ''">
      		<img :src="imgSrc(formData.companyLogoUrl)" />
      	</div>
        <el-upload
				  :action="baseUrl()"
				  list-type="picture-card"
				  :on-remove="handleRemove"
					ref="upload"
				  accept="image/jpeg,image/gif,image/png,image/bmp"
				  :auto-upload = "false"
				  :on-change="handleChangeImg"
					:before-remove="beforeRemove"
          :on-exceed="handleExceed"
					:limit="1"
					:file-list="fileList"
				  :drag="false"
				  >
				  <i class="el-icon-plus"></i>
				  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
				</el-upload>
				<el-dialog :visible.sync="dialogVisible" size="tiny">
				  <img width="100%" :src="dialogImageUrl" alt="">
				</el-dialog>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
			<el-button type="info" @click="submit('ruleForm','01')" :disabled="Subabled">保存草稿</el-button>
      <el-button type="info" @click="submit('ruleForm','02')" :disabled="Subabled">提交</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { queryCompanyList } from "@/services/companyRegist";
import { oneImgFromData} from "@/services/getFromData";
import { RequestError } from "@/services/errors";
import { mapActions } from "vuex";
import editorImage from "@/components/Tinymce/components/editorImage";
var serialize = require('form-serialize');
var vailMobile = (rule, value, callback) => {
	var MobileRegex = /^1[34578]\d{9}$/;
	if (!MobileRegex.test(value)) {
	    callback(new Error('企业联系人电话格式不正确！(仅支持手机号)'))
	    } else {
	        callback();
	    }
};
var vailNumber = (rule, value, callback) => {
	var NumberyRegex = /^[0-9]*$/;
	if (!NumberyRegex.test(value)) {
	    callback(new Error('格式不正确,只能输入数字'))
	    } else {
	        callback();
	    }
};
var vailEmail = (rule, value, callback) => {
	var emailRegex = /^[0-9A-Za-z][\.-_0-9A-Za-z]*@[0-9A-Za-z]+(\.[0-9A-Za-z]+)+$/;
	if (!emailRegex.test(value)) {
	    callback(new Error('企业联系人邮箱格式不正确！'))
	    } else {
	        callback();
	    }
};
export default {
  name: "edit-role",
  data () {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择权限'));
      } else {
        callback();
      }
    }
    return {
      menus: [],
      list: [],
			file:{},
			fileList:[],
			compList:[],
      formData: {
				companyNo:"",
        companyName: "",
        companyAddress: "",
        email: "",
        contractPerson: "",
        contractPhone: "",
				status: "",
				companyDesc:"",
				companyScale:"",
				companyType:""
			},
      imgShow:"",
      Subabled:false,
      dialogImageUrl: '',
      dialogVisible: false,
      dialogFormVisible: false,
      menuInfo: [],
      rules: {
        companyName: [{ required: true, message: "请输入企业名称", trigger: "blur" },
				{ min: 1, max: 50, message: '长度在 50个字符以内', trigger: 'blur' }],
				companyScale: [{ required: true, message: "请选择企业规模", trigger: "blur" }],
        companyDesc: [{ required: true, message: "请输入企业描述", trigger: "blur" },
        { min: 1, max: 200, message: '长度在 200个字符以内', trigger: 'blur' }],
        contractPerson: [{ required: true, message: "请输入企业联系人姓名", trigger: "blur" },
				{ min: 1, max: 20, message: '长度在 20个字符以内', trigger: 'blur' }],
				companyAddress: [{ required: true, message: "请输入企业地址", trigger: "blur" },
				{ min: 1, max: 100, message: '长度在 100个字符以内', trigger: 'blur' }],
				companyType: [{ required: true, message: "请输入企业类型", trigger: "blur" },
				{ min: 1, max: 10, message: '长度在 10个字符以内', trigger: 'blur' }],
        contractPhone: [
    			{ required: true, message: '请输入企业联系电话', trigger: 'blur' },
   			  { validator: vailMobile, trigger: 'blur'}
   			],
				email: [
    			{ required: true, message: '请输入邮箱', trigger: 'blur' },
   			  { validator: vailEmail, trigger: 'blur'}
        ], 
      }
    }
  },
  props: {
    view: {
      type: String,
      default: "create"
    }
  },
  methods: {
    ...mapActions(["setUserInfo"]),
    validateMobile(rule, value, callback) {
		   var MobileRegex = /^1[0-9]{10}$/;
		     if (!MobileRegex.test(value)) {
		         callback(new Error('手机号码格式不正确！'))
		     } else {
		         callback();
		     }
		},
		imgSrc(data){
      	return this.$store.state.imgUrl + data;
    },
    closeDialog() {
      this.$emit("close");
    },
    baseUrl(){
    	return "";
    },
		handleRemove(file, fileList) {
			this.file = ""
		},
		beforeRemove(file, fileList) {
			return this.$confirm(`确定移除 ${ file.name }？`);
		},
		handleExceed(files, fileList) {
			this.$message.warning(`当前限制只能导入 1 个文件`);
		},
    handleChangeImg(file, fileList){
				this.imgShow = ""
				this.regImage(file);
				this.regMemory(file);
				this.file = file.raw;
		},
		regMemory(file){
			const isLt10M = file.size / 1024 / 1024 < 2;
			if (!isLt10M) {
				this.$refs.upload.clearFiles();
				this.file = ""
				this.$message.error('上传图片大小不能超过 2MB!');
			}
		},
		regImage(file){
			var path = file.raw.name;  //得到的是现在文件的路径
			var Suffix = path.substr(path.lastIndexOf(".")).toUpperCase();//得到的是后缀名,且转换为大写
			// console.log(Suffix)
			if(Suffix != ".JPG" && Suffix !=".PNG" && Suffix !=".JPEG"){
					this.$refs.upload.clearFiles();
					this.file = ""
					this.$message.error('上传图片只能是 JPG/PNG 格式！');
			}
		},
		async loadCompList () {
			try {
				let data = await queryCompanyList();
				// console.log(data)
				this.compList = data.data;
			} catch (e) {
				if (e instanceof RequestError) {
					this.$alert(e.message, '提示', {
						type: 'error',
						confirmButtonText: '确定'
					})
				} else {
					throw e
				}
			}
			this.loading = false
		},
    submit(formName,status) {
			this.Subabled = true;
			this.butTimeOut();
      this.$refs[formName].validate(async valid => {
        if (valid) {
          try {
            if (this.view === "create") {
							//把图片的信息和参数放进请求头里
            	var sref = this;
            	//把图片的信息和参数放进请求头里
            	let code = await oneImgFromData({
				        companyName: this.formData.companyName,
				        companyAddress: this.formData.companyAddress,
				        email: this.formData.email,
				        contractPerson: this.formData.contractPerson,
				        contractPhone: this.formData.contractPhone,
								status: status,
								companyDesc:this.formData.companyDesc,
								companyScale:this.formData.companyScale,
								companyType:this.formData.companyType,
				      },"/ecshop/company/addCompanyInfo.do","companyLogo",sref.file).then(
								function(data){
									sref.$message({
										showClose: true,
										message: data,
										type: "success"
									});
									sref.$emit("close", true);
								}, 
								function(reason, data){
									sref.$message({
										showClose: true,
										message: reason,
										type: "error"
									});
								});
	          } 
            else {
              var sref = this;
            	//把图片的信息和参数放进请求头里
            	let code = await oneImgFromData({
				    		companyNo: this.formData.companyNo,
				    		companyName: this.formData.companyName,
				        companyAddress: this.formData.companyAddress,
				        email: this.formData.email,
				        contractPerson: this.formData.contractPerson,
				        contractPhone: this.formData.contractPhone,
								status: status,
								companyDesc:this.formData.companyDesc,
								companyScale:this.formData.companyScale,
								companyType:this.formData.companyType,
				      },"/ecshop/company/updateCompanyInfo.do","companyLogo",sref.file).then(
								function(data){
									sref.$message({
										showClose: true,
										message: data,
										type: "success"
									});
									sref.$emit("close", true);
								}, 
								function(reason, data){
									sref.$message({
										showClose: true,
										message: reason,
										type: "error"
									});
								});
            }
            this.dialogFormVisible = false;
          } catch (e) {
            if (e instanceof RequestError) {
              this.$alert(e.message, "提示", {
                type: "error",
                confirmButtonText: "确定"
              });
            } else {
              throw e;
            }
          }
        } else {
          return;
        }
      });
		},
		butTimeOut(){
			var serf = this;
			setTimeout(function(){
				serf.Subabled = false;
			},1200)
		}
  },
  mounted() {},
  components: {
      'editorImage': editorImage
    }
};
</script>
<style scoped>
.el-select {
  width: 100%;
}
.el-textarea__inner{
	height: 100px;
	resize:none;
}
.editImg{
	  overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    margin: 0 8px 8px 0;
    display: inline-block;
    float: left;
}
.editImg img{
	width: 100%;
	height: 100%;
}
</style>
